#include <stdio.h>
#include <climits>
#include <unistd.h>
#include <pthread.h>
#include "timer.h"

CTimer::CTimer()
{
	mTimes = 0;
	mParity = EVEN;
	mPeriodMillisecond = 0;
	mRunning = false;
	mTid = 0;
};

CTimer::~CTimer()
{
	pthread_exit(NULL);
};

int CTimer::StartTimer(unsigned long PeriodMillisecond)
{
	if(PeriodMillisecond == 0)
	{
		printf("Period can't be 0\n");
		return -1;
	}
	mPeriodMillisecond = PeriodMillisecond;
	if(!TimerCallBack)
	{
		printf("please set callback first\n");
		return -2;
	}
	int ret = pthread_create(&mTid, NULL, CheckTimeUP, this);
	if (ret != 0)
	{
		printf("pthread_create error: error_code= %d\n",ret);
	}
	mRunning = true;
	return ret;
}


void CTimer::StopTimer()
{
	mRunning = false;
}

int CTimer::test()
{
	if(TimerCallBack)
		TimerCallBack(mTimes,mParity);
}
void* CTimer::CheckTimeUP(void* arg)
{
	CTimer* p = (CTimer*)arg;
	while(1)
	{
		if(!mRunning)
			break;
		usleep(mPeriodMillisecond);
		mParity = !mParity;
		mTimes++;
		if(mTimes == ULONG_MAX)
		{
			mTimes = 0;
			printf("counter is max return to 0\n");
		}
		p->test();
	}
}
	

